import React from 'react';
import { createPortal } from 'react-dom';
import { IPortalProps, PortalIdType, PortalElementType } from './Portal.types';

const getContainer = (portalId: PortalIdType, portalElement: PortalElementType): Element | HTMLElement | null => {
    
    if (portalElement === undefined && portalId === undefined) {
        return document.body;
    }

    if (portalId) {
        return document.getElementById(portalId);
    }

    if (typeof portalElement === 'string') {
        return document.querySelector(portalElement);
    }

    if (typeof portalElement === 'function') {
        return portalElement();
    }

    return portalElement;
};

const Portal = React.forwardRef<Element | HTMLElement | null, IPortalProps>(({ children, portalId, portalElement }, ref) => {
    const [container, setContainer] = React.useState<Element | HTMLElement | null>(null);

    React.useLayoutEffect(() => {
        const portalContainer = getContainer(portalId, portalElement);
        setContainer(portalContainer);
    }, [portalId, portalElement]);

    const containerRef = React.useRef<Element | HTMLElement | null>(null);
    React.useImperativeHandle(ref, () => containerRef.current);

    return container ? <>{createPortal(children, container)}</> : <>{createPortal(<p>Контейнер не найден!</p>, document.body)}</>;
});

Portal.displayName = 'Portal';

export default Portal;
